const express = require("express");
const router = express.Router();
const db = require("../sql");
// 添加评论
router.post("/", async (req, res) => {
  const { userId, productId, content, rate } = req.body;
  if (!userId || !productId || !content || rate == null) {
    return res.status(400).json({ success: false, message: "缺少必要的参数" });
  }
  try {
    // 首先检查是否已存在该用户对该商品的评论
    const existingComment = await db.query(
      "SELECT id FROM comment WHERE userId = ? AND productId = ?",
      [userId, productId]
    );

    if (existingComment.length > 0) {
      // 如果已存在评论，返回错误信息
      return res.json({
        success: false,
        message: "您已对该商品发表过评论",
      });
    }

    const result = await db.query(
      "INSERT INTO comment (userId, content, rate, productId) VALUES (?, ?, ?, ?)",
      [userId, content, rate, productId]
    );
    res.json({
      success: true,
      message: "评论添加成功",
      commentId: result.insertId,
    });
  } catch (error) {
    res
      .status(500)
      .json({ success: false, message: "服务器错误", error: error.message });
  }
});

// 获取某个产品的评论列表
router.get("/product/:productId", async (req, res) => {
  const { productId } = req.params;
  try {
    const comments = await db.query(
      "SELECT c.*, u.userName, u.avatar FROM comment c JOIN user u ON c.userId = u.id WHERE c.productId = ? ORDER BY c.createTime DESC",
      [productId]
    );
    res.json({ success: true, comments });
  } catch (error) {
    res
      .status(500)
      .json({ success: false, message: "服务器错误", error: error.message });
  }
});

module.exports = router;
